<?php
/**
 * Created by .
 * User: luogan
 * Date: 2021/12/28
 */

declare(strict_types=1);

namespace App\Middleware;

use App\Constants\ErrorCode;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\Utils\Contracts\Arrayable;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

class CoreMiddleware extends \Hyperf\HttpServer\CoreMiddleware
{
    /**
     * @return array|Arrayable|mixed|ResponseInterface|string
     */
    protected function handleNotFound(ServerRequestInterface $request)
    {
        // 重写路由找不到的处理逻辑
        $data = api(ErrorCode::getMessage(ErrorCode::NOT_FOUND_ERROR),[],ErrorCode::NOT_FOUND_ERROR);
        // 阻止异常冒泡
        return $this->response()->withStatus(404)->withBody(new SwooleStream($data));

    }

    /**
     * @return array|Arrayable|mixed|ResponseInterface|string
     */
    protected function handleMethodNotAllowed(array $methods, ServerRequestInterface $request)
    {
        // 重写路由找不到的处理逻辑
        $data = api('Allow: ' . implode(', ', $methods),[],ErrorCode::METHOD_NOT_ALLOWED_ERROR);
        // 阻止异常冒泡
        return $this->response()->withStatus(405)->withBody(new SwooleStream($data));
    }
}
